package com.recharge.sup.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.recharge.OrderService;
import com.recharge.domain.Product;
import com.recharge.domain.Province;
import com.recharge.domain.TradeFlow;
import com.recharge.domain.TradeOrder;
import com.recharge.domain.TradeSupProductInfo;
import com.recharge.job.QueryOrderService;
import com.recharge.mapper.IProvinceMapper;
import com.recharge.mapper.ITradeOrderMapper;
import com.recharge.mapper.ITradeSupProductInfoMapper;
import com.recharge.sup.AbsSupChargeService;
import com.recharge.utils.HttpClientUtils;
import com.recharge.utils.ProcessResult;
import com.recharge.utils.ValueConvertUtils;

/**
 * 网池对接
 * @author qq
 *
 */
@Service
public class WangChiChargeServiceImpl extends AbsSupChargeService{

    @Value("${wangchill.sendFlowUrl}")
    private String sendFlowUrl ;

    @Value("${wangchill.queryOrderStatusId}")
    private String queryOrderStatusId ;

    @Value("${wangchill.userId}")
    private String userid ;

    @Value("${wangchill.wangchiId}")
    private String wangchiId ;
    
    @Value("${wangchill.callBackUrl}")
    private String notifyurl ;

    @Value("${wangchill.md5Key}")
    private String md5Key ;

    @Autowired
    private OrderService orderService;
    
    @Autowired
    private IProvinceMapper iProvinceMapper;

    @Autowired
    private ITradeOrderMapper iTradeOrderMapper;

    @Autowired
    private ITradeSupProductInfoMapper iTradeSupProductInfoMapper;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 充值
     * 返回订单充值结果
     */
    @Override
    public ProcessResult recharge(TradeOrder tradeOrder,TradeFlow tradeFlow) {
        String mobile = tradeOrder.getChargeNumber();      //充值号码
        String bizid = tradeOrder.getOrderId();            //商户订单号唯一
        
        String productname = tradeOrder.getProduct();
        TradeSupProductInfo wangchi= iTradeSupProductInfoMapper.selectToChannel(productname,"wangchi");
        String productid = wangchi.getChannelProductId();
        logger.info("查询到网池productid:{}", productid);  
        
        String key = DigestUtils.md5Hex(userid + mobile + productid + md5Key);//加密
        Map<String, String> params = new HashMap<String, String>();
        params.put("userid", userid);
        params.put("mobile", mobile);
        params.put("bizid", bizid);
        params.put("notifyurl", notifyurl);
        params.put("productid", productid);
        params.put("key", key);

        String result = null;
        try {
            logger.info("发送网池请求：{}",sendFlowUrl + "参数：" + params);
            result =HttpClientUtils.invokePostHttp(sendFlowUrl, params, "UTF-8", 3000); //发送页面地址
        } catch (Exception e) {
            logger.error("调用网池接口异常",e);
        }

        logger.info("wangchi return:{}",result);

        //判断充值结果
        if (result != null && !"".equals(result)) {
            Map<String, String> rspMap = jsonToObject(result);
            String orderId = rspMap.get("resultMsg"); //获取返回订单id
            String code = rspMap.get("resultCode");//获取返回code
            ProcessResult processResult = new ProcessResult();//实例化处理结果类

            if ("T00001".equals(code)) {                  //code等于T00001成功
                logger.info("orderid : {}发送成功",orderId);
                
                //修改订单处理状态为1（发送成功）
                iTradeOrderMapper.updateProcessStatus(bizid, "发送成功");
                
                processResult.setCode(ProcessResult.SUCCESS);//设置code为成功
                return processResult;
            }else if(StringUtils.equals("T00006",code)){   //code等于T00001余额不足
                logger.info("orderid : {}发送失败,账户余额不足",orderId);
                processResult.setCode(ProcessResult.FAIL);
              //修改订单处理状态为2（发送失败）
                iTradeOrderMapper.updateProcessStatus(bizid, "账户余额不足");
                return processResult;
            }else if(StringUtils.equals("T00007",code)){  //code等于T00007认证失败
                logger.info("orderid : {}发送失败,认证失败",orderId);
                processResult.setCode(ProcessResult.FAIL);
              //修改订单处理状态为2（发送失败）
                iTradeOrderMapper.updateProcessStatus(bizid, "认证失败");
                return processResult;

            }else if(StringUtils.equals("T00008",code)){   //code等于T00008系统异常
                logger.info("orderid : {}发送失败,系统异常",orderId);
                processResult.setCode(ProcessResult.FAIL);
              //修改订单处理状态为2（发送失败）
                iTradeOrderMapper.updateProcessStatus(bizid, "系统异常");
                return processResult;

            }else if(StringUtils.equals("T00009",code)){   //code等于T00009订单号已存在
                logger.info("orderid : {}发送失败,订单号已存在",orderId);//只打印日志不设置状态
              //修改订单处理状态为2（发送失败）
                iTradeOrderMapper.updateProcessStatus(bizid, "订单号已存在");
                //processResult.setCode(ProcessResult.UNKNOWN);
                return processResult;
            }
        }
      //修改订单处理状态为2（发送失败）
        iTradeOrderMapper.updateProcessStatus(bizid, "发送失败");
        logger.info("bizid:{}发送结果可疑",bizid );        //为空就发送可疑
        ProcessResult processResult = new ProcessResult();//实例化处理结果类
        processResult.setCode(ProcessResult.UNKNOWN);//设置code为未知
        return processResult;                        //返回未知结果.
    }

    /**
     * 查询
     * 返回订单处理结果
     */
    @Override
    public ProcessResult query(TradeOrder tradeOrder, TradeFlow tradeFlow) {
        ProcessResult processResult = new ProcessResult(); //实例化处理结果类
        String orderid="";                              //不是必须要系统订单id
        String bizid = tradeOrder.getOrderId();         //商户订单id（和系统订单id要有一个）
        String key = "";
        if(!"".equals(orderid) && !"".equals(bizid)){
            key = DigestUtils.md5Hex(userid + orderid + bizid + md5Key);//key加密
        }else if("".equals(orderid) && !"".equals(bizid)){
            key = DigestUtils.md5Hex(userid + bizid + md5Key);      //oraderid为空
        }else if(!"".equals(orderid) && "".equals(bizid)){
            key = DigestUtils.md5Hex(userid + orderid + md5Key);    //bizid为空
        }
        
        Map<String, String> params = new HashMap<String, String>();
        params.put("userid", userid);
        params.put("orderid", orderid);
        params.put("bizid", bizid);
        params.put("key", key);
        logger.info("SerialId: {}发送给上游查询，请求参数:{}",tradeFlow.getSerialId(),params);
        String result = null;
        try {
            result = HttpClientUtils.invokePostHttp(queryOrderStatusId, params, "utf-8", 3000);
        } catch (Exception e2) {
            logger.error("查询订单信息出错",e2);
        }
        logger.info("serialId: {} ,收到上游返回数据, responseData={}",tradeFlow.getSerialId() , result);


        if (result != null && !"".equals(result)) {             //result不为空和null
            Map<String, String> rspMap = jsonToObject(result);
            String code = rspMap.get("resultCode");             //获取参数code
            String msg = rspMap.get("resultMsg");				//获取订单状态
            if ("T00002".equals(code)) {                        //code等于T00002时查询成功
                if (StringUtils.equals("2",msg)){   
                    processResult.setCode(ProcessResult.SUCCESS);//设置处理结果为成功
                }else if(StringUtils.equals("0",msg)){
                    logger.info("bizid:{}未发货",bizid);
                    processResult.setCode(ProcessResult.PROCESSING);//设置处理结果为处理中
                }else if(StringUtils.equals("1",msg)){
                    logger.info("bizid:{}发货中",bizid);
                    processResult.setCode(ProcessResult.PROCESSING);//设置处理结果为处理中
                }else if(StringUtils.equals("3",msg)){
                    logger.info("bizid:{}发货失败",bizid);
                    processResult.setCode(ProcessResult.FAIL);//设置处理结果为失败
                }
                return processResult;
            }else if (StringUtils.equals("T00007",code)){
                logger.info("订单查询失败");
                processResult.setCode(ProcessResult.FAIL);//设置处理结果为失败
                return processResult;                     //返回失败结果
            }else if(StringUtils.equals("T00010",code)){
                logger.info("订单orderid: {}和bizid: {}不存在",orderid,bizid);
                processResult.setCode(ProcessResult.FAIL);
                return processResult;                     
            }
        }
        //结果为空就设置未知
        processResult.setCode(ProcessResult.UNKNOWN);
        return  processResult;//返回未知结果
    }

    /**
     * 回调
     */
    @Override
    public void response(TradeOrder tradeOrder,TradeFlow tradeFlow,Map<String,String> responseMap) {
        String resultCode = responseMap.get("resultCode");//获取map中错误errorCode
        
    	//修改订单处理状态为3（回调过）
        String orderid = tradeOrder.getOrderId();
        if (StringUtils.equals("T00003",resultCode)){     //等于suss时
            orderService.SUCCESS(tradeOrder,tradeFlow);
        }else if (StringUtils.equals("T00004",resultCode)){
            orderService.FAIL(tradeOrder, tradeFlow);     //调用fall方法
        }else{
            orderService.UNKNOWN(tradeOrder, tradeFlow);//调用unkown方法
        }
    }


    public static Map<String,String> jsonToObject(String jsonStr){
        Map<String, String> map = new HashMap<String, String>();
        map= (Map<String, String>) JSON.parseObject(jsonStr, HashMap.class);
        return map;
    }
    
}